package dev.mcdd.security.adapter;


import dev.mcdd.user.entity.Role;
import dev.mcdd.user.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * SecurityUserDetailsAdapter
 *
 * @author: mcdd1024
 * @date 2025/1/16 06:41
 */
public record SecurityUserDetailsAdapter(User user) implements UserDetails {

    public SecurityUserDetailsAdapter {
        Objects.requireNonNull(user);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        Role role = user.getRole();
        authorities.add(SecurityGrantedAuthorityAdapter.role(role.getName()));
        role.getPermissions().forEach(permission -> authorities.add(SecurityGrantedAuthorityAdapter.permission(permission.getName())));
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isEnabled() {
        return user.getEnable();
    }


}
